package com.wstuo.common.security.service;

import com.wstuo.common.security.dao.IOrganizationDAO;
import com.wstuo.common.security.dao.IServiceTimeDAO;
import com.wstuo.common.security.dto.ServiceTimeDTO;
import com.wstuo.common.security.entity.Organization;
import com.wstuo.common.security.entity.ServiceTime;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.transaction.annotation.Transactional;

/**
 * 服务时间业务
 * 
 */
public class ServiceTimeService implements IServiceTimeService {
	@Autowired
	private IServiceTimeDAO serviceTimeDAO;
	@Autowired
	private IOrganizationDAO organizationDAO;

	/**
	 * 根据机构编号查找服务时间.
	 * 
	 * @param orgNo
	 *            机构编号：Long orgNo
	 * @return 服务机构DTO：ServiceTimeDTO
	 */
	public ServiceTimeDTO findServiceTimeByOrgNo(Long orgNo) {
		ServiceTime entity = serviceTimeDAO.findByOrgNo(orgNo);
		ServiceTimeDTO dto = new ServiceTimeDTO();
		if (entity != null) {
			ServiceTimeDTO.entity2dto(entity, dto);
			if (entity.getOrganization() != null) {
				dto.setOrgNo(entity.getOrganization().getOrgNo());
			}
		}

		return dto;
	}

	/**
	 * 保存或新增服务时
	 * 
	 * @param dto
	 *            数据DTO:ServiceTimeDTO
	 */
	@Transactional()
	public void saveOrUpdateServiceTime(ServiceTimeDTO dto) {
		ServiceTime serviceTime = null;
		Long sid = dto.getSid();
		if (sid != null) {
			serviceTime = serviceTimeDAO.findById(sid);
		} else {// 避免重复
			serviceTime = serviceTimeDAO.findByOrgNo(dto.getOrgNo());
		}
		// 不存在创建
		if (serviceTime == null) {
			serviceTime = new ServiceTime();
		}
		serviceTime.setOrganization(organizationDAO.findById(dto.getOrgNo()));
		dto.setSid(serviceTime.getSid());
		ServiceTimeDTO.dto2entity(dto, serviceTime);
		ServiceTime serviceTimeM = serviceTimeDAO.merge(serviceTime);
		dto.setSid(serviceTimeM.getSid());
		// 关联
		Organization org = organizationDAO.findById(dto.getOrgNo());
		org.setServiceTime(serviceTimeM);
		organizationDAO.merge(org);
	}
}
